package com.luoqiz.project.screenBroadcard.client;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import com.luoqiz.project.screenBroadcard.ScreenOper;

public class UIRefreshThread extends Thread {

	private ClientUI clientUI;
	private boolean flag = false;

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	public UIRefreshThread(ClientUI clientUI) {
		this.clientUI = clientUI;
	}

	@Override
	public void run() {
		DatagramSocket receiver = null;
		ScreenOper sp = new ScreenOper();
		try {
			receiver = new DatagramSocket(16000);
			System.out.println("开始接收广播");
			byte[] screenData = new byte[1024 * 62];
			DatagramPacket pack = new DatagramPacket(screenData, screenData.length);
			long timestampTemp = 0l;
			// List<Long,Map<Integer, ScreenDataInfo>> map = new ArrayList<Long,Map<Integer,
			// ScreenDataInfo>>();
			Map<Integer, ScreenDataInfo> map = new HashMap<Integer, ScreenDataInfo>();
			while (flag) {
				receiver.receive(pack);
				int len = pack.getLength();
				ScreenDataInfo sdi = sp.recr(screenData, len);
				// System.out.println("****时间:" + sdi.getTiemstamp() + "---索引：" +
				// sdi.getPackageIndex());
				if (sdi.getTiemstamp() > timestampTemp) {
					if (!map.isEmpty()) {
						processScreen(map);
					}
					timestampTemp = sdi.getTiemstamp();
					map.clear();
					map.put(sdi.getPackageIndex(), sdi);
				} else if (sdi.getTiemstamp() == timestampTemp) {
					map.put(sdi.getPackageIndex(), sdi);
				} else {
					continue;
				}
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			receiver.close();
		}
	}

	private void processScreen(Map<Integer, ScreenDataInfo> map) {
		if (map.size() == 0) {
			System.out.println("初始化");
			return;
		}
		if (map.size() != map.get(0).getPackageCount()) {
			System.out.println("丢包了");
			return;
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			for (int i = 0, n = map.size(); i < n; i++) {
				baos.write(map.get(i).getContent());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		BufferedImage b = null;
		try {
			b = ImageIO.read(new ByteArrayInputStream(baos.toByteArray()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		clientUI.imageShow.setIcon(new ImageIcon(b));
		clientUI.repaint();
	}
}
